#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import scrapy
import json
import math
import time
import urllib.parse

from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class XinjiangChangjishiQuPolicy(BaseTaxPolicySpider):
    name = 'xinjiang_changjishi_qu_policy'
    
    province = '新疆维吾尔自治区'
    city: str = "昌吉回族自治州"  # 取表格
    # county: str = ""  # 取表格
    park: str = ""  # 取表格
    custom_settings = {
        "DOWNLOAD_TIMEOUT": 60
    }

    def start_requests(self):
        for source, county, url in [
            ['昌吉市人民政府', "昌吉市", "https://www.cjs.gov.cn/info/iList.jsp?isSd=false&node_id=GKcjszf&cat_id=28069&tm_id=2619&cur_page=1&q=zc"],
            ['昌吉市人民政府', "昌吉市", "https://www.cjs.gov.cn/info/iList.jsp?node_id=GKcjszf&cat_id=28070&tm_id=2619&q=zc&w=zbwj"],
            ['昌吉市人民政府', "昌吉市", "https://www.cjs.gov.cn/info/iList.jsp?node_id=GKcjszf&cat_id=33910&tm_id=2619&q=zc&w=gfxwj"],
            ['昌吉市人民政府', "昌吉市", "https://www.cjs.gov.cn/info/nIndex.jsp?node_id=GKcjskjj&cat_id=23976"],
            ['昌吉市人民政府', "昌吉市", "https://www.cjs.gov.cn/info/nIndex.jsp?node_id=GKcjsny&cat_id=24322"],
            ['昌吉市人民政府', "昌吉市", "https://www.cjs.gov.cn/info/nIndex.jsp?node_id=GKcjsjx&cat_id=24307"],
            ['昌吉市人民政府', "昌吉市", "https://www.cjs.gov.cn/info/nIndex.jsp?node_id=GKcjssb&cat_id=24286"],
            ['昌吉市人民政府', "昌吉市", "https://www.cjs.gov.cn/info/nIndex.jsp?node_id=GKcjswg&cat_id=24278"],
            ['昌吉市人民政府', "昌吉市", "https://www.cjs.gov.cn/info/nIndex.jsp?node_id=GKcjstyjr&cat_id=33965"],
            ['昌吉市人民政府', "昌吉市", "https://www.cjs.gov.cn/info/nIndex.jsp?node_id=GKcjsfg&cat_id=24181"],
            ['昌吉市人民政府', "昌吉市", "https://www.cjs.gov.cn/info/nIndex.jsp?node_id=GKcjscz&cat_id=23921"],
            ['木垒哈萨克自治县人民政府', "木垒哈萨克自治县", "https://www.mlx.gov.cn/info/iList.jsp?node_id=GKmlxzf&cat_id=33832&tm_id=2594&q=zc&w=gfxwj"],
            ['木垒哈萨克自治县人民政府', "木垒哈萨克自治县", "https://www.mlx.gov.cn/info/iList.jsp?node_id=GKmlxzf&cat_id=33884&tm_id=2574&q=zc&w=zfwj"],
            ['木垒哈萨克自治县人民政府', "木垒哈萨克自治县", "https://www.mlx.gov.cn/info/iList.jsp?node_id=GKmlxzf&cat_id=26178&tm_id=2574&q=zc&w=zbwj"],
            ['奇台县人民政府', "奇台县", "https://www.xjqt.gov.cn/info/iList.jsp?isSd=false&node_id=GKqtzfb&cat_id=28916&tm_id=2638&q=zc&w=zbw"],
            ['奇台县人民政府', "奇台县", "https://www.xjqt.gov.cn/info/iList.jsp?isSd=false&node_id=GKqtzf&cat_id=33938&tm_id=2638&q=zc&w=gfx"],
            ['呼图壁县人民政府', "呼图壁县", "https://www.htb.gov.cn/info/iList.jsp?node_id=GKhtzjzf&cat_id=34082&tm_id=2590&q=zcc&w=zwcj"],
            ['呼图壁县人民政府', "呼图壁县", "https://www.htb.gov.cn/info/iList.jsp?node_id=GKhtzjzf&cat_id=34083&tm_id=2590&q=zcc&w=zbwj"],
            ['呼图壁县农业农村局', "呼图壁县", "https://www.htb.gov.cn/info/nIndex.jsp?node_id=GKhtbnyj"],
            ['呼图壁县商务工信局', "呼图壁县", "https://www.htb.gov.cn/info/nIndex.jsp?node_id=GKhtbsjw"],
            ['呼图壁县民政局', "呼图壁县", "https://www.htb.gov.cn/info/nIndex.jsp?node_id=GKhtbmzj"],
            ['阜康市人民政府', "阜康市", "https://www.fk.gov.cn/info/iList.jsp?node_id=GKfkzf&cat_id=33896&tm_id=2639&q=zc&w=zfwj"],
            ['阜康市人民政府', "阜康市", "https://www.fk.gov.cn/info/iList.jsp?node_id=GKfkzf&cat_id=27413&tm_id=2639&q=zc&w=zfbwj"],
            ['阜康市人民政府', "阜康市", "https://www.fk.gov.cn/info/iList.jsp?node_id=GKfkzf&cat_id=34146&tm_id=2639&q=zc&w=gfxwj"],
        ]:
            params = dict(urllib.parse.parse_qsl(urllib.parse.urlparse(url).query))
            if 'info/iList.jsp' in url:
                callback = self.parse_list
            else:
                callback = self.parse_content
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=callback, meta={'item': item, 'params': params})

    def parse_content(self, response, **kwargs):
        params = response.meta.get('params')
        params['cur_page'] = "1"
        tm_id = response.xpath("//iframe[@id='rightFrame']/@src").re_first(r"&tm_id=(\d+)")
        if tm_id:
            params['tm_id'] = tm_id
        yield response.follow("/info/iList.jsp" + '?' + urllib.parse.urlencode(params), callback=self.parse_list,
                              meta=response.meta)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        elem_list = response.xpath(
                "//div[@class='zfxxgk_right']//td//a[contains(@href, 'htm') or @title]/ancestor::td[string-length(string(.))>=5] |"
                "//div[@class='zfxxgk_right' or @class='mainList']//li//a[contains(@href, 'htm') or @title]/ancestor::li[string-length(string(.))>=5] |"
                "//table[@class]//tr/td/a[contains(@href, 'htm') or @title]/ancestor::td[string-length(string(.))>=5]")
        for elem in elem_list:
            item = Item()
            item['source_url'] = elem.xpath("""./a/@href""").re_first(r"""(.*)""")
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            # if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
            #     continue
            # if 'list.shtml' in item['source_url']:
            #     continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            pages = response.xpath(".").re_first(r"""共\s*(\d+)\s*页""") or response.xpath(".").re_first(r"""第\d+/(\d+)\s*页""")
            params = response.meta['params']
            print(response.url, f"page: {pages}")
            for page_num in range(2, int(pages) + 1):
                params['cur_page'] = str(page_num)
                yield response.follow("/info/iList.jsp" + '?' + urllib.parse.urlencode(params), callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath("//*[@class='fbrq']/text()").get()
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl xinjiang_changjishi_qu_policy".split())
